/*
 * NumberedSequence.cpp
 *
 *  Created on: Oct 28, 2013
 *      Author: m
 */

#include "Sequence.h"

namespace ipc
{

Sequence::Sequence( std::string file, char charKey ) :
    m_mutex( Semaphore::get( file, charKey ) ),
    m_currentValue( SharedMemory<snumber_t>::get( file, charKey ) )
{
}

Sequence::~Sequence()
{
}

int Sequence::getNext()
{
    int number;

    m_mutex.p();

    number = m_currentValue.read();
    number++;
    m_currentValue.write( number );

    m_mutex.v();

    return number;
}

Sequence Sequence::create( std::string file, char charKey )
{
    Semaphore sem = Semaphore::create( file, charKey, 1 );
    sem.initialize( 1 );

    SharedMemory<snumber_t> shm = SharedMemory<snumber_t>::create(
            file, charKey, 1 );
    shm.initialize( 0 );

    return Sequence( file, charKey );
}

Sequence Sequence::get( std::string file, char charKey )
{
    return Sequence( file, charKey );
}

void Sequence::destroy( std::string file, char charKey )
{
    Semaphore::destroy( file, charKey );
    SharedMemory<snumber_t>::destroy( file, charKey );
}

} /* namespace ipc */
